import tornado.gen
import httplib2
import urllib
import json
import hashlib
import traceback
class AutodeployModel():
    def __init__(self):
        print ("this is init for AutodeployModel")
    @tornado.gen.coroutine
    def fnPush(self, data):
        ret = True
        try:
            #print(data)
            #print(type(data))
            message = {}
            '''
            contents_dict = {}
            atMobiles_dict = {}
            atMobiles = []
            atMobiles.append('13983063899')
            atMobiles_dict['atMobiles'] = atMobiles
            atMobiles_dict['isAtAll'] = 'false'
            contents_dict['content'] = str(data['total_commits_count']) + " new commit " + "by " + data['user_name']
            message_text_dict = {}
            message_text_dict['msgtype'] = 'text'
            message_text_dict['text'] = contents_dict
            message_text_dict['at'] = atMobiles_dict
        '''
            link_contents_dict = {}
            link_contents_dict['text'] = str(data['total_commits_count']) + " new commit " + "by " + data['user_name'] + "\n " \
            + "注释: " + data['commits'][0]['message'] + "\n" \
            + "提交时间: " + data['commits'][0]['timestamp']
            link_contents_dict['title'] = "码云平台 - " + data['project']['path_with_namespace']
            link_contents_dict['picUrl'] = ""
            link_contents_dict['messageUrl'] = data['commits'][0]['url']

            message_link_dict = {}
            message_link_dict['msgtype'] = 'link'
            message_link_dict['link'] = link_contents_dict

            message = message_link_dict
            print(message)
            print(type(message))
        except Exception as e:
            print ("Exception occur in fnPush %s" % e)
            ret = False
        finally:
            if ret:
                return (message)
    @tornado.gen.coroutine
    def send_message_to_dingtalk(self, data):
        ret = True
        try:
            if "humoumou" in data['link']['title']:
                hosturl_slave = "https://oapi.dingtalk.com/robot/send?access_token=2ab447c0ef053ee1a19e74422f88376dddef11404286330f37bd7418ccb6c39d"
            if "advertisement_backend_api" in data['link']['title']:
                hosturl_slave = "https://oapi.dingtalk.com/robot/send?access_token=2ab447c0ef053ee1a19e74422f88376dddef11404286330f37bd7418ccb6c39d"
            data = json.dumps(data)
            hosturl = 'https://oapi.dingtalk.com/robot/send?access_token=c1966e626338b42475b5e89e6d6ff26f46c9c216f5288dc11c876e363e4f03e8'
            headers = {"Content-type": "application/json","Accept": "text/plain"}
            conn = httplib2.Http(".cache")
            response,content = conn.request(hosturl, 'POST',data, headers)
            print (content.decode('utf-8'))
            if hosturl_slave is not None:
                response,content = conn.request(hosturl_slave, 'POST',data, headers)
                print (content.decode('utf-8'))
        except Exception as e:
            print ("Exception occur in send_message_to_dingtalk %s" % e)
            ret = False
        finally:
            if ret:
                print ("success")

    @tornado.gen.coroutine
    def check_auth(self, data):
        ret = True
        try:
            name = data['terminal_name']
            timestramp = str(data['timestramp'])
            password = data['auth']
            name = bytes(name, encoding = "utf8")
            timestramp = bytes(timestramp, encoding = "utf8")
            #print(type(name))
            #print(type(timestramp))
            m = hashlib.md5()
            m.update(name)
            m.update(timestramp)
            m.update(b"6sB<n8PpZ{}chV5yUB7a")
            md5value=m.hexdigest()
            #print(md5value)
            if password==md5value:
                print("check ok")
                ret = True
            else:
                print("check failed %s" % data['terminal_name'])
                ret = False
        except Exception as e:
            print ("Exception occur in check_auth %s" % e)
            print('traceback.format_exc():\n%s' % traceback.format_exc())
            ret = False
        finally:
            if ret:
                print ("success")
            return ret

    @tornado.gen.coroutine
    def get_ctl_result(self, data):
        terminal_list = []
        ret = True
        try:
            ret = yield self.check_auth(data)
            if ret:
                with open("remotectl.conf","r",encoding="utf-8") as f:
                    lines = f.readlines()
                    for line in lines:
                        print(line)
                        terminal_list.append(line)
            else:
                ret = False
        except Exception as e:
            print ("Exception occur in get_ctl_result %s" % e)
            print('traceback.format_exc():\n%s' % traceback.format_exc())
            ret = False
        finally:
            if ret:
                print ("get_ctl_result success")
                return terminal_list
    @tornado.gen.coroutine
    def disable_remote_access_by_terminal_name(self, data):
        ret = True
        try:
            ret = yield self.check_auth(data)
            if ret:
                with open("remotectl.conf","r",encoding="utf-8") as f:
                    lines = f.readlines()
                    #print(lines)
                with open("remotectl.conf","w",encoding="utf-8") as f_w:
                    for line in lines:
                        if data['terminal_name'] in line:
                            continue
                        f_w.write(line)
            else:
                ret = False
        except Exception as e:
            print ("Exception occur in get_ctl_result %s" % e)
            print('traceback.format_exc():\n%s' % traceback.format_exc())
            ret = False
        finally:
            if ret:
                print ("disable_remote_access_by_terminal_name success")
            return ret

